package com.kele.test.rabbitmq.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
public class RabbitMQConfig_DeadLetter {

    private static final String QUEUE_NAME_BUSINESS = "queue_dlx_business";
    private static final String EXCHANGE_BUSINESS_NAME = "exchange_dlx_business_direct";
    private static final String ROUTINGKEY_BUSINESS = "business";


    private static final String QUEUE_NAME_DEADLETTER = "dlx_deadletter_queue";
    private static final String EXCHANGE_DEADLETTER_NAME = "dlx_exchange_deadletter_direct";
    private static final String ROUTINGKEY_DEADLETTER = "deadletter";

    @Bean(QUEUE_NAME_BUSINESS)
    public Queue queueDeclare_dlx_business(){
        //return new Queue(QUEUE_NAME,true);
        Queue queue =  QueueBuilder.durable(QUEUE_NAME_BUSINESS)
                //.deadLetterExchange(EXCHANGE_DEADLETTER_NAME)
                .withArgument("x-dead-letter-exchange", EXCHANGE_DEADLETTER_NAME)
                //.deadLetterRoutingKey(ROUTINGKEY_DEADLETTER)
                .withArgument("x-dead-letter-routing-key", ROUTINGKEY_DEADLETTER)
                .maxLength(1000)
                .ttl(10000)//10s
                .build();
        return queue;
    }

    @Bean(EXCHANGE_BUSINESS_NAME)
    public Exchange exchangeDeclare_dlx_business(){
        return ExchangeBuilder.directExchange(EXCHANGE_BUSINESS_NAME).durable(true).build();
    }

    @Bean
    public Binding bindingDeclare_dlx_business1(
            @Qualifier(QUEUE_NAME_BUSINESS) Queue queue,
            @Qualifier(EXCHANGE_BUSINESS_NAME) Exchange exchange){
        return BindingBuilder.bind(queue).to(exchange).with(ROUTINGKEY_BUSINESS).noargs();
    }

    //死信绑定
    @Bean(QUEUE_NAME_DEADLETTER)
    public Queue queueDeclare_dlx_deadletter(){
        //return new Queue(QUEUE_NAME,true);
        Queue queue =  QueueBuilder.durable(QUEUE_NAME_DEADLETTER)
                .build();
        return queue;
    }

    @Bean(EXCHANGE_DEADLETTER_NAME)
    public Exchange exchangeDeclare_dlx_deadletter(){
        return ExchangeBuilder.directExchange(EXCHANGE_DEADLETTER_NAME).durable(true).build();
    }

    @Bean
    public Binding bindingDeclare_dlx_deadletter(
            @Qualifier(QUEUE_NAME_DEADLETTER) Queue queue,
            @Qualifier(EXCHANGE_DEADLETTER_NAME) Exchange exchange){
        return BindingBuilder.bind(queue).to(exchange).with(ROUTINGKEY_DEADLETTER).noargs();
    }
}
